/**
 * 
 */
package io.dora.registry.zk;

import io.dora.conf.ServiceURL;
import io.dora.registry.AbstractRegistry;

import java.io.IOException;

import io.dora.registry.curator.CuratorRegistry;
import org.apache.commons.lang.StringUtils;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * zookeeper服务注册中心实现
 * 
 * @author zhaohongbo
 *
 */
public class ZkRegistry extends AbstractRegistry {

	private Logger logger = LoggerFactory.getLogger(ZkRegistry.class);
	
	private ZooKeeper zk;
	
	public ZkRegistry(String url) {
		try {
			zk = new ZooKeeper(url, 3000, new Watcher() {
				@Override
				public void process(WatchedEvent event) {
					logger.info("WatchedEvent:{}", event.toString());
				}
			});
		} catch (IOException e) {
			logger.error("{}", e);
		}
	}
	

	@Override
	public void register(ServiceURL serviceURL)  {
		boolean flag = ZkUtils.createNode(zk, serviceURL.getPath());
		if (flag) {
			ZkUtils.addOrUpdateNodeData(zk, serviceURL.getPath(), serviceURL.getHost() + ":" + serviceURL.getPort(), true);
		}
	}

	@Override
	public void lookup(String serviceKey) {
		String data = ZkUtils.getNodeData(zk, serviceKey);
		if (StringUtils.isNotBlank(data)) {
			serviceMap.put(serviceKey, data);
		}
	}


	@Override
	public void subscribe(String serviceKey) {
		
	}

}
